

<!DOCTYPE html>
<html lang="en" color-mode=light>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>多线程同步 - 习武的个人博客</title>
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="google" content="notranslate" />
  
  <meta name="description" content="在进行项目开发时经常会遇到这样一个场景：当多个请求完成...">
  <meta name="author" content="习武">
  <link rel="icon" href="/xiwu_see/images/icons/favicon-16x16.png" type="image/png" sizes="16x16">
  <link rel="icon" href="/xiwu_see/images/icons/favicon-32x32.png" type="image/png" sizes="32x32">
  <link rel="apple-touch-icon" href="/xiwu_see/images/icons/apple-touch-icon.png" sizes="180x180">
  <meta rel="mask-icon" href="/xiwu_see/images/icons/stun-logo.svg" color="#333333">
  
    <meta rel="msapplication-TileImage" content="/xiwu_see/images/icons/favicon-144x144.jpeg">
    <meta rel="msapplication-TileColor" content="#000000">
  

  
<link rel="stylesheet" href="/xiwu_see/css/style.css">


  
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1445822_s6x2xcokxrl.css">

  

  
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">

  

  
    
      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/xcode.min.css" name="highlight-style" mode="light">

      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/solarized-dark.min.css" name="highlight-style" mode="dark">

      
  

  <script>
    var CONFIG = window.CONFIG || {};
    var ZHAOO = window.ZHAOO || {};
    CONFIG = {
      isHome: false,
      fancybox: true,
      pjax: false,
      lazyload: {
        enable: true,
        only_post: 'false',
        loading: '/xiwu_see/images/theme/loading.gif'
      },
      donate: {
        enable: false,
        alipay: 'https://pic.izhaoo.com/alipay.jpg',
        wechat: 'https://pic.izhaoo.com/wechat.jpg'
      },
      galleries: {
        enable: true
      },
      fab: {
        enable: true,
        always_show: false
      },
      carrier: {
        enable: true
      },
      daovoice: {
        enable: false
      },
      preview: {
        background: {
          default: '/xiwu_see/images/theme/welcome-image.jpg',
          api: ''
        },
        motto: {
          default: '我在开了灯的床头下，想问问自己的心啊。',
          api: 'https://v2.jinrishici.com/one.json',
          data_contents: '["data","content"]'
        },
      },
      qrcode: {
        enable: false,
        type: 'url',
        image: 'https://pic.izhaoo.com/weapp-code.jpg',
      },
      toc: {
        enable: true
      },
      scrollbar: {
        model: 'simple'
      },
      notification: {
        enable: false,
        delay: 4500,
        list: '',
        page_white_list: '',
        page_black_list: ''
      }
    }
  </script>

  

  

<meta name="generator" content="Hexo 5.3.0"></head>

<body class="lock-screen">
  <div class="loading"></div>
  


  <nav class="navbar">
    <div class="left">
      
      
        <i class="iconfont iconmoono" id="color-toggle" color-toggle="light"></i>
      
    </div>
    <div class="center">多线程同步</div>
    <div class="right">
      <i class="iconfont iconmenu j-navbar-menu"></i>
    </div>
    
  </nav>

  

<nav class="menu">
  <div class="menu-wrap">
    <div class="menu-close">
      <i class="iconfont iconbaseline-close-px"></i>
    </div>
    <ul class="menu-content"><li class="menu-item">
        <a href="/xiwu_see/ " class="underline "> 首页</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/archives/ " class="underline "> 归档</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/tags/ " class="underline "> 标签</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/categories/ " class="underline "> 分类</a>
      </li><li class="menu-item">
        <a href="/xiwu_see/about/ " class="underline "> 关于</a>
      </li></ul>
    
      <div class="menu-copyright"><p>Powered by <a target="_blank" href="https://hexo.io">习武</a>  |  Theme - <a target="_blank" href="https://xiwu123.gitee.io/xiwu_see">习武的个人博客</a></p></div>
    
  </div>
</nav>
  <main id="main">
  <div class="article-wrap">
    <div class="row container">
      <div class="col-xl-3"></div>
      <div class="col-xl-6"><article class="article">
  <div class="wrap">
    <section class="head">
  <img   class="lazyload" data-original="/xiwu_see/images/theme/theme-iOS-4.jpeg" src=""  draggable="false">
  <div class="head-mask">
    <h1 class="head-title">多线程同步</h1>
    <div class="head-info">
      <span class="post-info-item"><i class="iconfont iconcalendar"></i>April 01, 2020</span>
      
      <span class="post-info-item"><i class="iconfont iconfont-size"></i>3672</span>
    </div>
  </div>
</section>
    <section class="main">
      <section class="content">
        <p>在进行项目开发时经常会遇到这样一个场景：当多个请求完成时，最后执行某个业务逻辑。一看上去这就是一个多线程控制同步的问题，常见的解决方案有三种。</p>
<ul>
<li>每个请求定义一个变量，然后在每个请求执行完后的block里执行最后执行业务逻辑的方法，方法里必然有着这几个变量的真判断。</li>
<li>使用队列NSOperationQueue控制多线程同步。</li>
<li>使用信号量dispatch_semaphore_t控制多线程同步。</li>
<li>使用进程同步dispatch_group_t控制多线程同步。</li>
</ul>
<hr>
<h3 id="比较及实现方式"><a href="#比较及实现方式" class="headerlink" title="比较及实现方式"></a>比较及实现方式</h3><ul>
<li><p> 第一种看上去很粗浅，就是每次请求就去判断一次各个变量，都通过了表示请求完成了，然后执行最后的业务逻辑。当然这种最好写，但是会加大内存开销和业务复杂度，一方面是有几个请求就得定义几个变量，程序运行时需要进行内存分配，另外还要维护每个变量的真假业务逻辑，如果存在刷新之类的操作更是如此，更有甚者，如果是几十上百个请求，难道要定义几十上百个变量，所以对于简单的多线程请求，稍微多一些或者复杂一些的不建议使用。不过，现在这种方式一般见不到。</p>
</li>
<li><p>第二种队列NSOperationQueue面向对象方式，多用于请求之间存在依赖关系，如果不存在依赖关于请求的完成无法控制，所以不存在依赖则这种方式一般不建议使用。</p>
</li>
</ul>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs objectivec"><span class="hljs-built_in">NSBlockOperation</span> *operation_1 = [<span class="hljs-built_in">NSBlockOperation</span> blockOperationWithBlock:^&#123;<br><span class="hljs-built_in">NSLog</span>(<span class="hljs-string">@&quot;1&quot;</span>);<br>[<span class="hljs-keyword">self</span> loadUserFriendsData];<br>&#125;];<br><span class="hljs-built_in">NSBlockOperation</span> *operation_2 = [<span class="hljs-built_in">NSBlockOperation</span> blockOperationWithBlock:^&#123;<br><span class="hljs-built_in">NSLog</span>(<span class="hljs-string">@&quot;2&quot;</span>);<br>[<span class="hljs-keyword">self</span> loadBalaceData];<br>&#125;];<br><span class="hljs-built_in">NSBlockOperation</span> *operation_3 = [<span class="hljs-built_in">NSBlockOperation</span> blockOperationWithBlock:^&#123;<br><span class="hljs-built_in">NSLog</span>(<span class="hljs-string">@&quot;3&quot;</span>);<br>[<span class="hljs-keyword">self</span> loadUserData];<br>&#125;];<br><span class="hljs-comment">//设置依赖关系</span><br>[operation_2 addDependency:operation_3];<br>[operation_1 addDependency:operation_2];<br><span class="hljs-comment">//创建队列并添加任务 （这里要设置No）</span><br><span class="hljs-built_in">NSOperationQueue</span> *queue = [[<span class="hljs-built_in">NSOperationQueue</span> alloc]init]; [queue addOperations:@[operation_3,operation_2,operation_1] waitUntilFinished:<span class="hljs-literal">NO</span>];<br><span class="hljs-comment">//注意这里一定要是No,不然会阻塞线程</span><br></code></pre></td></tr></table></figure>
<ul>
<li> 第三种使用信号量dispatch_semaphore_t和使用dispatch_group_t有异曲同工之妙，所以这里直接上代码，怎么使用。</li>
</ul>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs reasonml"><span class="hljs-comment">//创建信号</span><br>dispatch_semaphore_t sema = dispatch<span class="hljs-constructor">_semaphore_create(0)</span>;<br><span class="hljs-comment">//发射信号</span><br>dispatch<span class="hljs-constructor">_semaphore_signal(<span class="hljs-params">sema</span>)</span>;<br><span class="hljs-comment">//等待信号</span><br>dispatch<span class="hljs-constructor">_semaphore_wait(<span class="hljs-params">sema</span>, DISPATCH_TIME_FOREVER)</span>;<br></code></pre></td></tr></table></figure>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs awk">(void)request2&#123;<br><span class="hljs-regexp">//</span>创建信号量并设置计数默认为<span class="hljs-number">0</span><br>dispatch_semaphore_t semaphore = dispatch_semaphore_create(<span class="hljs-number">0</span>);<br>NSDictionary * para ;<span class="hljs-regexp">//</span>参数 具体部分我就不暴露了<br>[WJFCollection postWithUrlString:@<span class="hljs-string">&quot;url&quot;</span> Parameter:para success:^(id responseObject) &#123;<br><span class="hljs-regexp">//</span>只要在这里发送信号<br>dispatch_semaphore_signal(semaphore);<br>&#125; failure:^(NSError *error) &#123;<br><span class="hljs-regexp">//</span>只要在这里发送信号<br>dispatch_semaphore_signal(semaphore);<br>NSLog(@<span class="hljs-string">&quot;%@&quot;</span>,error);<br>&#125;];<br><span class="hljs-regexp">//</span>若计数为<span class="hljs-number">0</span>则一直等待<br>dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);<br>&#125;<br></code></pre></td></tr></table></figure>
<ul>
<li> 第四种使用dispatch_group_t，使用方式如下</li>
</ul>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs reasonml">dispatch_group_t group = dispatch<span class="hljs-constructor">_group_create()</span>;<br>dispatch<span class="hljs-constructor">_group_async(<span class="hljs-params">group</span>, <span class="hljs-params">dispatch_get_global_queue</span>(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)</span>, ^&#123;<br><span class="hljs-literal">[<span class="hljs-identifier">self</span> <span class="hljs-identifier">requestData</span>]</span>;<br>&#125;) ;<br>dispatch<span class="hljs-constructor">_group_async(<span class="hljs-params">group</span>, <span class="hljs-params">dispatch_get_global_queue</span>(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)</span>, ^&#123;<br><span class="hljs-literal">[<span class="hljs-identifier">self</span> <span class="hljs-identifier">requestData</span>]</span>;<br>&#125;) ;<br>dispatch<span class="hljs-constructor">_group_async(<span class="hljs-params">group</span>, <span class="hljs-params">dispatch_get_global_queue</span>(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)</span>, ^&#123;<br><span class="hljs-literal">[<span class="hljs-identifier">self</span> <span class="hljs-identifier">requestData</span>]</span>;<br>&#125;) ;<br>dispatch<span class="hljs-constructor">_group_notify(<span class="hljs-params">group</span>, <span class="hljs-params">dispatch_get_main_queue</span>()</span>, ^&#123;<br><span class="hljs-comment">//展示页面</span><br><span class="hljs-literal">[<span class="hljs-identifier">self</span> <span class="hljs-identifier">showUserView</span>]</span>;<br>&#125;);<br></code></pre></td></tr></table></figure>
<figure class="highlight lasso"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs lasso">- (<span class="hljs-literal">void</span>)requestData &#123;<br>    dispatch_group_enter(<span class="hljs-built_in">self</span>.<span class="hljs-keyword">group</span>);<br>    WeakSelf<br>    <span class="hljs-meta">[</span><span class="hljs-built_in">self</span>.VMModel request:^(id model, NSError * _Nonnull error) &#123;<br>        StrongSelf<br>        <span class="hljs-keyword">if</span> (strongSelf) &#123;<br>            dispatch_group_leave(strongSelf.<span class="hljs-keyword">group</span>);<br>        &#125;<br>    &#125;<span class="hljs-meta">]</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p> dispatch_semaphore和dispatch_group在使用方式上大同小异，但是dispatch_semaphore相对而言更涉及到底层，越底层使用起来越灵活，自定义程度越高，但是使用起来就会越复杂，而dispatch_group是在信号量dispatch_semaphore_t基础上进行的一层封装，所以使用起来方便一些。从使用对象来说，dispatch_group更加针对的是任务、进程而非线程，所以整体性处理起来更快捷。关于两者的层级请看dispatch_group_leave的源码使用。</p>
</blockquote>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs reasonml">void dispatch<span class="hljs-constructor">_group_leave(<span class="hljs-params">dispatch_group_t</span> <span class="hljs-params">dg</span>)</span><br>&#123;<br>    dispatch_semaphore_t dsema = (dispatch_semaphore_t)dg;<br>    dispatch<span class="hljs-constructor">_atomic_release_barrier()</span>;<br>    long value = dispatch<span class="hljs-constructor">_atomic_inc2o(<span class="hljs-params">dsema</span>, <span class="hljs-params">dsema_value</span>)</span>;<span class="hljs-comment">//dsema_value原子性加1</span><br>    <span class="hljs-keyword">if</span> (slowpath(value<span class="hljs-operator"> == </span>LONG_MIN)) &#123;<span class="hljs-comment">//内存溢出，由于dispatch_group_leave在dispatch_group_enter之前调用</span><br>        <span class="hljs-constructor">DISPATCH_CLIENT_CRASH(<span class="hljs-string">&quot;Unbalanced call to dispatch_group_leave()&quot;</span>)</span>;<br>    &#125;<br>    <span class="hljs-keyword">if</span> (slowpath(value<span class="hljs-operator"> == </span>dsema-&gt;dsema_orig)) &#123;<span class="hljs-comment">//表示所有任务已经完成，唤醒group</span><br>        (void)<span class="hljs-constructor">_dispatch_group_wake(<span class="hljs-params">dsema</span>)</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
      </section>
      <section class="extra">
        
          <ul class="copyright">
  
    <li><strong>本文作者：</strong>习武</li>
    <li><strong>本文链接：</strong><a href="https://gitee.com/xiwu123/xiwu_see.git/2020/04/01/iOS/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5%E4%BD%BF%E7%94%A8/index.html" title="https:&#x2F;&#x2F;gitee.com&#x2F;xiwu123&#x2F;xiwu_see.git&#x2F;2020&#x2F;04&#x2F;01&#x2F;iOS&#x2F;%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5%E4%BD%BF%E7%94%A8&#x2F;index.html">https:&#x2F;&#x2F;gitee.com&#x2F;xiwu123&#x2F;xiwu_see.git&#x2F;2020&#x2F;04&#x2F;01&#x2F;iOS&#x2F;%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5%E4%BD%BF%E7%94%A8&#x2F;index.html</a></li>
    <li><strong>版权声明：</strong>本博客所有文章均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" title="BY-NC-SA" target="_blank" rel="noopener">BY-NC-SA</a> 许可协议，转载请注明出处！</li>
  
</ul>
        
        
        
  <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/xiwu_see/tags/%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5-NSOperation-dispatch-semaphore-t-dispatch-group-t-%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E5%90%8C%E6%AD%A5/" rel="tag">线程同步, NSOperation, dispatch_semaphore_t, dispatch_group_t, 多线程, 同步</a></li></ul> 

        
  <nav class="nav">
    <a href="/xiwu_see/2020/04/01/iOS/dispatch_group%E5%BC%95%E8%B5%B7%E7%9A%84%E5%BC%82%E5%B8%B8/"><i class="iconfont iconleft"></i>dispatch_group同步异常问题</a>
    <a href="/xiwu_see/2019/12/21/%E4%BA%8C%E6%AC%A1%E5%85%83/%E4%BA%8C%E6%AC%A1%E5%85%83/">帝子降兮北渚，目眇眇兮愁予<i class="iconfont iconright"></i></a>
  </nav>

      </section>
      
    </section>
  </div>
</article></div>
      <div class="col-xl-3">
        
          
  <aside class="toc-wrap">
    <h3 class="toc-title">文章目录：</h3>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%AF%94%E8%BE%83%E5%8F%8A%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F"><span class="toc-text">比较及实现方式</span></a></li></ol>
  </aside>

        
      </div>
    </div>
  </div>
</main>
  

<footer class="footer">
  <div class="footer-social"><a 
        href="tencent://message/?Menu=yes&uin=756364924 "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#12B7F5'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconQQ "></i>
      </a><a 
        href="javascript:; "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#09BB07'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconwechat-fill "></i>
      </a><a 
        href="https://github.com/xiwuxisheng "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#9f7be1'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  icongithub-fill "></i>
      </a><a 
        href="756364924@qq.com "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color=#FF3B00" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconmail"></i>
      </a></div>
  
    <div class="footer-copyright"><p>Powered by <a target="_blank" href="https://hexo.io">习武</a>  |  Theme - <a target="_blank" href="https://xiwu123.gitee.io/xiwu_see">习武的个人博客</a></p></div>
  
</footer>
  
      <div class="fab fab-plus">
    <i class="iconfont iconplus"></i>
  </div>
  
  
  <div class="fab fab-up">
    <i class="iconfont iconcaret-up"></i>
  </div>
  
  
    <div class="scrollbar j-scrollbar">
  <div class="scrollbar-current j-scrollbar-current"></div>
</div>
  
  
    
<script src="/xiwu_see/js/color-mode.js"></script>

  
</body>

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>



  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>




  
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>








<script src="/xiwu_see/js/utils.js"></script>
<script src="/xiwu_see/js/script.js"></script>





  <script>
    (function () {
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      } else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>













</html>